#! /usr/bin/env python3
# -*- coding -*-

import unit_strategy
import param_cache
import os
import logging
from aiocoap import *
import asyncio
import json
import common

logging.basicConfig(level=logging.INFO)


class UnitRequestProcess(unit_strategy.UnitObject):

    def process1(self, paramc: param_cache.ParamCache):
        self.saveinfo = {}
        self.paramc = paramc
        gcon = paramc.get_param_request_com()
        self.dest = gcon['destination']
        self.filtrate = gcon['filtrate']
        self.url = gcon['url']
        self.config_reload_request(paramc.get_param_config())
        uri = self.dest + self.url
        logging.info("request info :")
        logging.info(uri)
        asyncio.get_event_loop().run_until_complete(
            self.coap_send(uri)
        )
        # logging.info(self.paramc.get_save_info())
        return self.paramc


    def config_reload_request(self, con):
        self.savekey = con['savekey']
        self.searchkey = con['searchkey']

        # self.payload = con['payload']
        # self.type = con['type']
        # self.url = con['url']
        # self.comparison = con['comparison']

    async def coap_send(self, uri):
        context = await Context.create_client_context()
        await asyncio.sleep(2)
        request = Message(code=Code.GET, uri=uri)
        response = await context.request(request).response
        logging.info('Result: %s \n %r' % (response.code, response.payload))
        result = response.payload.decode('ascii')
        self.find_section(result)

    def find_section(self, jsonstring):
        result = common.FindSection(jsonstring, self.filtrate, self.searchkey)
        self.saveinfo[self.savekey] = result
        self.paramc.add_save_info(self.saveinfo)


if __name__ == '__main__':
    data1 = r'{"name":"BeJson","url":"http://www.bejson.com","page":88,"isNonProfit":true}'
    data2 = r'{"url":"http://www.bejson.com","name":"BeJson","page":88,"isNonProfit":true}'
    json1 = json.loads(data1)
    json2 = json.loads(data2)
    if sorted(json1) != sorted(json2):
        print("failed")
    for key, value in json2.items():
        if value == '##NOCHECK':
            continue

        if json1[key] != value:
            print("value failed ")

    print("success")
